package LC;

import java.util.Stack;

/**
 * https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
 * Evaluate the value of an arithmetic expression in Reverse Polish Notation.
 * Valid operators are +, -, *, /. Each operand may be an integer or another expression.
 * Some examples:
 * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
 * ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
 */
public class LC_150_EvaluateReversePolishNotation_Stack {
    public static void main(String[] args) {
        System.out.println(Solution.evalRPN(new String[]{"2", "3", "+", "5", "*"}));
    }

    static class Solution {
        static int evalRPN(String[] tokens) {
            if (tokens == null || tokens.length < 1)
                throw new IllegalArgumentException();
            int op1;
            int op2;
            Stack<Integer> stack = new Stack<>();
            for (String token : tokens) {
                if ("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token)) {
                    op2 = stack.pop();
                    op1 = stack.pop();
                    switch (token.charAt(0)) {
                        case '+':
                            op1 += op2;
                            break;
                        case '-':
                            op1 -= op2;
                            break;
                        case '*':
                            op1 *= op2;
                            break;
                        case '/':
                            op1 /= op2;
                            break;
                    }
                    stack.push(op1);
                } else {
                    stack.push(Integer.parseInt(token));
                }
            }
            return stack.pop();
        }
    }
}